// backend/src/websocket.js
const WebSocket = require('ws');
const logger = require('./logger');

class WebSocketServer {
  constructor(port) {
    this.port = port;
    this.clients = new Set();  // 改用Set存储客户端
    this.initialize();
  }

  initialize() {
    this.wss = new WebSocket.Server({
      port: this.port,
      host: '0.0.0.0'
    });

    this.wss.on('connection', (ws) => {
      this.clients.add(ws);
      logger.info(`New client connected. Total clients: ${this.clients.size}`);

      ws.on('message', (message) => {
        try {
          logger.info(`Received message: ${message.toString()}`);
          // 广播给其他所有客户端
          this.clients.forEach(client => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
              client.send(message.toString());
            }
          });
        } catch (error) {
          logger.error(`Error handling message: ${error}`);
        }
      });

      ws.on('close', () => {
        this.clients.delete(ws);
        logger.info(`Client disconnected. Remaining clients: ${this.clients.size}`);
      });
    });

    logger.info(`WebSocket server started on port ${this.port}`);
  }
}

module.exports = WebSocketServer;
